package com.xuecheng.web.interceptors;

import com.alibaba.fastjson.JSON;
import com.xuecheng.commons.model.vo.AuthInfo;
import com.xuecheng.commons.utils.AuthInfoHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;

/**
 * 自定义拦截器
 */
public class AuthInfoInterceptor implements HandlerInterceptor {

    /**
     * 进入controller方法之前执行
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、获取请求头中的payload
        String payload = request.getHeader("payload");
        if (StringUtils.isEmpty(payload)) {
            return true;
        }
        //2、转化编码
        String json = URLDecoder.decode(payload, "utf-8");
        //3、转化成AuthInfo对象
        AuthInfo info = JSON.parseObject(json, AuthInfo.class);
        //4、存入ThreadLocal
        AuthInfoHolder.setAuthInfo(info);
        //true：向后执行controller方法
        return true;
    }

    /**
     * 在响应结束之前
     */
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
